import type { NavigationGuardNext, RouteLocationNormalized, RouteRecordRaw } from "vue-router";
import NProgress from "@/utils/nprogress";
import { getToken } from "@/utils/auth";
import router from "@/router";
import { usePermissionStore, useUserStore } from "@/store";
import { type AdminModel } from "@/model/admin-model";

export function setupPermission() {
  // 白名单路由
  const whiteList = ["/login"];

  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const isLogin = getToken(); // 判断是否登录

    const title = (to.params.title as string) || (to.query.title as string);
    if (title) {
      to.meta.title = title;
    }

    if (isLogin) {
      if (to.path === "/login") {
        // 已登录，访问登录页，跳转到首页
        next({ path: "/" });
        return;
      }

      // 是否已生成了路由列表
      const permissionStore = usePermissionStore();
      if (!permissionStore.isRoutesLoaded) {
        // 生成动态路由
        const dynamicRoutes = await permissionStore.generateRoutes();
        dynamicRoutes.forEach((route: RouteRecordRaw) => router.addRoute(route));
        next({ ...to, replace: true });
        return;
      }

      // 是否获取到了管理员信息
      const userInfo: AdminModel | undefined = await useUserStore().userInfo;
      if (!userInfo) {
        await useUserStore().getUserInfo();
      }
      next();
    } else {
      // 未登录，判断是否在白名单中
      if (whiteList.includes(to.path)) {
        next();
      } else {
        // 不在白名单，重定向到登录页
        redirectToLogin(to, next);
        NProgress.done();
      }
    }
  });

  // 后置守卫，保证每次路由跳转结束时关闭进度条
  router.afterEach(() => {
    NProgress.done();
  });
}

// 重定向到登录页
function redirectToLogin(to: RouteLocationNormalized, next: NavigationGuardNext) {
  const params = new URLSearchParams(to.query as Record<string, string>);
  const queryString = params.toString();
  const redirect = queryString ? `${to.path}?${queryString}` : to.path;
  next(`/login?redirect=${encodeURIComponent(redirect)}`);
}

/** 判断是否有权限 */
export function hasAuth(value: string | string[], type: "button" | "role" = "button") {
  console.log(value, type, "hasAuth");
  // TODO：待实现
  // const { roles, perms } = useUserStore().userInfo;
  // // 超级管理员 拥有所有权限
  // if (type === "button" && roles.includes("ROOT")) {
  //   return true;
  // }
  // const auths = type === "button" ? perms : roles;
  // return typeof value === "string"
  //   ? auths.includes(value)
  //   : value.some((perm) => auths.includes(perm));
}
